package student.web.internal;

import java.util.Map;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventThreadInit;

import cloudspace.stats.StatEvent;
import cloudspace.stats.StatisticsService;
import cloudspace.vm.VM;


/**
 * This thread is run when each event within the event pool is assigned to
 * handle a client side event sent to the server.
 * 
 * @author mjw87
 * 
 */
public class VMTagInit implements EventThreadInit
{

    public boolean init( Component comp, Event event ) throws Exception
    {
        VM.lookupVM().enter();
        PersistentStorageManager PSM = PersistentStorageManager.getInstance( "shared" );
        ApplicationSupportStrategy strat = LocalityService.getSupportStrategy();
        Map<String, PersistentStorageManager.StoredObject> context = (Map<String, PersistentStorageManager.StoredObject>)strat.getSessionParameter( "context-object" );
        if ( context != null )
            for ( String key : context.keySet() )
                if ( context.get( key ) != null )
                    if ( PSM.hasFieldSetChanged( key, context.get( key )
                        .timestamp() ) )
                        PSM.getPersistentObject( key, VM.currentVM()
                            .getLoader() );
        // This filters out any events kicked off by the internal CloudSpace UI
        if ( ( event.getTarget() != null && !event.getTarget()
            .getClass()
            .getPackage()
            .getName()
            .startsWith( "cloudspace." ) )
            && !comp.getId().startsWith( "_CSUI" ) )
        {
            StatisticsService.getStatService()
                .observe( new StatEvent( "EventsFired" ) );
            VM.currentVM().log.println( event.getName()
                + " event has occurred on component "
                + event.getTarget().getId() );
        }
        return true;
    }


    public void prepare( Component comp, Event event ) throws Exception
    {
        ;
    }

}
